/*  This file is part of -_-.

    -_- is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    -_- is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with -_-.  If not, see <http://www.gnu.org/licenses/>.

    Copyright 2012 Oliver Katz */

#include "extendability.h"

ExtensionEnv::ExtensionEnv()
{
}

ExtensionEnv::ExtensionEnv(string n, AST s, AST p)
{
	name = n;
	self = s;
	parent = p;
}

string ExtensionEnv::getName()
{
	return name;
}

AST ExtensionEnv::getSelf()
{
	return self;
}

AST ExtensionEnv::getParent()
{
	return parent;
}

Extension::Extension()
{
	callback = NULL;
}

Extension::Extension(string n, ExtensionCallback c)
{
	name = n;
	callback = c;
}

string Extension::getName()
{
	return name;
}

AST Extension::eval(AST self, AST parent)
{
	ExtensionEnv env = ExtensionEnv(name, self, parent);
	return callback(env);
}

ExtensionManager::ExtensionManager()
{
}

int ExtensionManager::add(Extension e)
{
	extensions[e.getName()] = e;
	return 0;
}

Extension ExtensionManager::get(string n)
{
	return extensions[n];
}

AST ExtensionManager::extend(AST page, AST parent)
{
	AST tmp = page;
	for (map<string, Extension>::iterator i = extensions.begin(); i != extensions.end(); i++)
		tmp = i->second.eval(tmp, parent);
	AST rtn = AST(tmp.get());
	vector<AST> b = tmp.getBranches();
	for (vector<AST>::iterator i = b.begin(); i != b.end(); i++)
		rtn.branch(extend(*i, page));
	return rtn;
}

AST ExtensionManager::extend(AST page)
{
	return extend(page, AST());
}

